<template>
  <el-dialog v-model="dialogFormVisible" :close-on-click-modal="false" class="dialog-wrap">
    <template #header>
      <div class="dialog-title">
        {{ title }}
      </div>
    </template>

    <div class="w">
      <div class="filter">
        <div class="filter-l"></div>
        <div class="filter-r"><table-filter @save="filterChange" /></div>
      </div>

      <!-- 表格 -->
      <table-body ref="table" v-model="selection" v-loading="loading" class="body" :list="list" />

      <!-- 翻页 -->
      <div class="footer">
        <el-pagination
          v-model:page-size="queryData.pageSize"
          v-model:current-page="queryData.pageNum"
          layout="total,->,prev, pager, next ,sizes ,jumper"
          :pager-count="5"
          :total="pageTotal"
          background
          @size-change="request"
          @current-change="request"
        />
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm(ruleForm)">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import $api from './api.js'
import { extend } from '@/utils/tool.js'
import TableFilter from './student-add-filter.vue'
import TableBody from './student-add-body.vue'

const emits = defineEmits(['save'])
const { proxy } = getCurrentInstance()

// data
const dialogFormVisible = ref(false)
const title = ref('选择班级学生')
const selection = ref([])
const list = ref([])
const queryData = ref({
  noClassId: '',
  pageNum: 1,
  pageSize: 10,
})
const loading = ref(false)
const pageTotal = ref(0)

// 方法
async function load(classId) {
  dialogFormVisible.value = true
  await nextTick()
  reset()

  queryData.value.noClassId = classId
  request()
}

function reset() {
  queryData.value.pageNum = 1
  queryData.value.pageSize = 10
  queryData.value.noClassId = ''
  list.value = []
}

function request() {
  const sendData = {
    ...queryData.value,
  }
  loading.value = true
  $api
    .studentList(sendData)
    .then((res) => {
      list.value = []
      list.value = res.rows
      pageTotal.value = res.total
    })
    .finally(() => {
      loading.value = false
    })
}

function filterChange(d) {
  queryData.value = {
    ...queryData.value,
    ...d,
  }
  queryData.value.pageNum = 1
  request()
}

function submitForm() {
  emits('save', selection.value)
  dialogFormVisible.value = false
}

defineExpose({
  load,
})
</script>

<style lang="scss" scoped>
.w {
  .filter {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  .body {
    margin-bottom: 20px;
    height: 550px;
  }
  .footer {
    margin-bottom: 20px;
  }
}
</style>
